import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base_widget/code7/provider/demo1/time_counter_model.dart';
import 'package:provider/provider.dart';
import 'dart:async';


///代码清单 7-7-1
///lib/code7/provider/demo1/consumer_page.dart
void main() => runApp(
  ChangeNotifierProvider(
    create: (BuildContext context) {
      return TimeCounterModel();
    },
    child: const MaterialApp(
      ///默认的首页面
      home: ConsumerTimePage(),
    ),
  ),
);

///代码清单 7-7-2
class ConsumerTimePage extends StatefulWidget {
  const ConsumerTimePage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _TestABPageState();
  }
}
class _TestABPageState extends State {
  ///计时器
  Timer? _timer;
  @override
  void initState() {
    super.initState();
    ///间隔1秒执行时间
    _timer = Timer.periodic(const Duration(milliseconds: 1000), (timer) {
      ///发送事件
      Provider.of<TimeCounterModel>(context,listen: false).getCurrentTime(); //2
    });
  }
  @override
  void dispose() {
    super.dispose();
    ///取消计时器
    _timer!.cancel();
  }
  @override
  Widget build(BuildContext context) {
    ///页面主体脚手架
    return const Scaffold(
      body: Center(child: BPage(),),
    );
  }
}

///代码清单 7-7-2
class BPage extends StatelessWidget{
  const BPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<TimeCounterModel>(
      ///参数 value 就是绑定的事件结果 TimeCounterModel
      builder: (BuildContext context, value, Widget ?child) {
        return Container(
          ///外边距
          margin: EdgeInsets.only(left: 12, top: 12),
          child: Text(
            '${value.formatTime}',
            style: TextStyle(fontSize: 22.0, color: Colors.red),
          ),
        );
      },
    );
  }
}